package bb.lanxing.model.database;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import bb.lanxing.util.JsonUtil;

public class Bbs extends LitePalTableBase {
    public String userHead;
    public String createBy;

    public String content;
    public ArrayList<String> imageList;
    public ArrayList<String> largeImageList;

    public ArrayList<Integer> typeList = new ArrayList<>();

    public String createTime;
    public int contentsCount;
    public int likesCount;

    public int serverId;

    public int myLike;
    public int userId;

    public static Bbs createByJson(JSONObject jSONObject) {
        Bbs bbs = new Bbs();

        bbs.setId(null);

        bbs.userHead = JsonUtil.getStringValue("avatar", jSONObject);
        bbs.createBy = JsonUtil.getStringValue("createBy", jSONObject);

        bbs.content = JsonUtil.getStringValue("content", jSONObject);
        JSONArray jsonArray = JsonUtil.getArrayValue("files", jSONObject);
        if (jsonArray.length() > 0) {
            bbs.largeImageList = new ArrayList<>();
            bbs.imageList = new ArrayList<>();
            try {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String fileUrl = jsonArray.getJSONObject(i).optString("fileUrl");
                    if (!"".equals(fileUrl)) {
                        bbs.largeImageList.add(fileUrl);
                        if (!fileUrl.endsWith("HEIC")) {
                            String[] fileUrls = fileUrl.split("/");
                            if (fileUrls.length > 0) {
                                fileUrls[fileUrls.length - 1] = "thumb_" + fileUrls[fileUrls.length - 1];
                                fileUrl = String.join("/", fileUrls);
                            }
                        }
                        bbs.imageList.add(fileUrl);
                    }
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }

        bbs.createTime = JsonUtil.getStringValue("createTime", jSONObject);
        bbs.contentsCount = JsonUtil.getIntegerValue("contentsCount", jSONObject);
        bbs.likesCount = JsonUtil.getIntegerValue("likeNum", jSONObject);

        bbs.serverId = JsonUtil.getIntegerValue("id", jSONObject);
        bbs.myLike = JsonUtil.getIntegerValue("myLike", jSONObject);
        bbs.userId = JsonUtil.getIntegerValue("userId", jSONObject);

        return bbs;
    }
}